package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2023/2/5 15:18
 * @Version 1.0
 */
@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private IScheduleClient scheduleClient;

    @Autowired
    private WmNewsAutoScanService autoScanService;
    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Override
    public void addTask(WmNews wmNews) {
        Task task = new Task();
        task.setTaskType(1001);
        task.setExecuteTime(wmNews.getPublishTime().getTime());
        task.setPriority(1);

        WmNews taskNews = new WmNews();
        taskNews.setId(wmNews.getId());

        task.setParameters(ProtostuffUtil.serialize(taskNews));
        scheduleClient.addTask(task);
        log.info("添加任务成功");
    }

//    @Scheduled(fixedRate = 5000)
    public void poll(){
        log.info("开始获取需要执行的任务");
        ResponseResult result = scheduleClient.poll(1001, 1);
        log.info("--->任务平台返回：{}",JSON.toJSONString(result));
        if(result.getCode() == AppHttpCodeEnum.SUCCESS.getCode() && result.getData() != null){
            String jsonString = JSON.toJSONString(result.getData());
            Task task = JSON.parseObject(jsonString,Task.class);
            byte[] parameters = task.getParameters();
            WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
            //注意：提交到任务平台的news里面只包含id，所以这里要重新查询一次
            WmNews news = wmNewsMapper.selectById(wmNews.getId());
            autoScanService.autoScan(news);
        }
    }

}